from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView

from apps.user.utils import JwtAuthentication
from celery_tasks.sms.tasks import ccp_send_sms_code
from .serializers import UserSerializer
from rest_framework.generics import CreateAPIView, UpdateAPIView
import random
import logging
from apps.user.models import User
logger = logging.getLogger('django')

class UserRegisterView(CreateAPIView):
    # 用户注册
    serializer_class = UserSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class SMSCodeView(APIView):
    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_codes')

        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_403_FORBIDDEN)

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info('短信验证码为: %s' % sms_code)

        pl = redis_conn.pipeline()

        pl.set('sms_%s' % mobile, sms_code,)

        pl.set('send_flag_%s' % mobile, 1)

        pl.execute()

        ccp_send_sms_code.delay(mobile, sms_code)

        return Response({'message': '发送成功',
                        'success': 'ok',
                        'sms_code':sms_code
                         })


from rest_framework_jwt.views import JSONWebTokenAPIView
from apps.user.serializers import AdminJSONWebTokenSerializer
# from apps.user.models import User

class AdminJsonWebTokenAPIView(JSONWebTokenAPIView):

    serializer_class = AdminJSONWebTokenSerializer

admin_jwt_token=AdminJsonWebTokenAPIView.as_view()




from apps.user.serializers import UserInfoSerializer, UserLabelSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import RetrieveUpdateAPIView



# 个人中心
class UserInfoView(ModelViewSet):
    authentication_classes = [JwtAuthentication]
    serializer_class = UserInfoSerializer
    queryset = User.objects.all()
    def get_queryset(self):
        username = self.request.user['username']
        user = User.objects.filter(username=username)
        return user

    def update(self, request, *args, **kwargs):
        username = self.request.user["username"]
        User.objects.filter(username=username).update(**request.data)
        instance = User.objects.get(username=username)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

from rest_framework import generics
class UserLabelAPIview(generics.GenericAPIView):
    queryset = User.objects.all()
    serializer_class = UserLabelSerializer

    def put(self, request):
        labels = request.data['labels']
        id = request.user.id
        instance = User.objects.get(id=id)
        for label in instance.labels.all():
            instance.labels.remove(label)
            instance.save()
        for label in labels:
            instance.labels.add(label)
            instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)


class ChangePsdView(APIView):
    def put(self, request):
        password = request.data.get('password')
        user = request.user
        user.set_password(password)
        user.save()
        return Response({"success": True,
                         "message": "OK"})



class FollowUsersView(APIView):
    def post(self, request, id):
        current_user = request.user  #当前用户
        aim_user = User.objects.get(id=id) #目标用户
        fans = aim_user.fans.all()
        if current_user not in fans:
            aim_user.fans.add(current_user)
            return Response(data={
                "message": "关注成功！",
                "success": True
            })

    def delete(self, request, id):
        current_user = request.user  #当前用户
        aim_user = User.objects.get(id=id) #目标用户
        fans = aim_user.fans.all()
        if current_user in fans:
            aim_user.fans.remove(current_user)
            return Response(data={
                "message": "取消关注成功！",
                "success": True
            })






